<script setup>
import { computed, ref } from 'vue'
import { useRouter } from 'vue-router';
import { useUserStore } from '@/store';
import { showToast } from 'vant';

import { fetchWithdrawalOptions } from '@/api/withdraw'

import AccountCard from './components/accountCard.vue'

import BiPopup from '@/components/biPopup/index.vue'
import BiNavBar from '@/components/biNavbar/index.vue'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(true)
function handleStopLoading() {
    loading.value = false
}

const withdrawOptions = ref([])
async function handleFetchWithdrawalOptions() {
    try {
        const res = await fetchWithdrawalOptions({ device: userStore.uuid })
        withdrawOptions.value = res.data.data
        handleStopLoading()
    } catch (error) {
        throw new Error(error)
    }
}
handleFetchWithdrawalOptions()

const targetAmount = computed(() => {
    const target = withdrawOptions.value.find(item => {
        return userStore.coin <= item.coin
    })
    return target || { coin: 0, amount: 0 }
})
const bannerPorgressWidth = computed(() => {
    const rate = Math.round((userStore.coin / targetAmount.value.coin) * 100)
    return Number.isFinite(rate) ? rate : 0
})

function useProgressStyle(coin) {
    const result = Math.round((userStore.coin / coin) * 100)
    return { '--item-progress-width': `${result}%` }
}
function handleCouldExchange(coin) {
    return userStore.coin > coin
}

const showPopup = ref(false)
function handleOpenPopup() {
    showPopup.value = true
}

const currentOption = ref({})
function handleToInput(option) {
    currentOption.value = option

    if (!userStore.finishNewbieTask) {
        showToast('Unable to withdraw funds without completing the novice benefits')
        return
    }

    if (userStore.coin < option.coin) {
        handleOpenPopup()
        return
    }

    const query = {
        balance: option.dollar,
        withdrawType: 1 // 金币提现
    }
    router.push({ path: '/input', query })
}

function handleToGetRewards() {
    const hasBrokenEggCount = userStore.eggCount < 30
    const hasTurntableCount = userStore.turntableCount < 30

    if (hasBrokenEggCount) {
        router.push('/egg')
        return
    }

    if (hasTurntableCount) {
        router.push('/turntable')
        return
    }

    if (!hasBrokenEggCount && !hasTurntableCount) {
        router.push('/egg')
        return
    }
}
</script>

<template>
    <BiNavBar title="Exchange" @click-left="router.back">
        <template v-slot:right>
            <RouterLink :to="{ path: '/flow' }">
                <div class="to-flow">
                    <img class="to-flow_icon" src="@/assets/imgs/exchange/flow.png" alt="toFlowIcon" width="40">
                </div>
            </RouterLink>
        </template>
    </BiNavBar>

    <div class="progress">
        <h1 class="progress-title">Next Payout for ${{ Number.parseFloat(targetAmount.dollar).toFixed(2) }}</h1>
        <div class="progress-bar">
            <div class="progress-bar-info" :style="{ '--progress-width': `${bannerPorgressWidth}%` }">
                <svg height="100%">
                    <text ref="text" class="progress-bar-info_text" text-anchor="middle" x="50%" y="70%">
                        {{ userStore.coin }} / {{ targetAmount.coin }} Coins
                    </text>
                </svg>
            </div>
        </div>
    </div>

    <AccountCard :cash="userStore.cash" />

    <main class="main">
        <div class="withdraw">
            <van-loading v-if="loading" style="position: fixed;top: 50%;left: 50%;transform: translate(-50%, -50%);"
                vertical color="#f2456b" text-color="#f2456b">
                Loading...
            </van-loading>
            <ul v-else class="withdraw-grid">
                <li class="withdraw-card" v-for="item in withdrawOptions" :key="item.id">
                    <div class="withdraw-card-container" @click="handleToInput(item)">
                        <span class="withdraw-card-container_span">${{ Number.parseFloat(item.dollar).toFixed(2)
                            }}</span>
                        <img src="@/assets/imgs/exchange/logo_big.png" alt="paypal" width="100"
                            class="withdraw-card-container_img">
                        <div class="withdraw-card-container_btn" :style="useProgressStyle(item.coin)">
                            <span v-if="handleCouldExchange(item.coin)">Exchange</span>
                            <template v-else>
                                <img src="@/assets/imgs/coin.png" alt="coin" width="30">
                                <span>{{ item.coin }}</span>
                            </template>
                        </div>
                    </div>
                </li>
            </ul>
        </div>
    </main>

    <!-- 提醒用户金币或签到天数不足 -->
    <BiPopup v-model:show="showPopup" type="withdraw" :withdrawStatus="false" @click="handleToGetRewards">
        <div class="failed">
            <span v-if="currentOption.coin == 1000" style="font-size: 3.3vmin;">Complete all beginner tasks</span>
            <span>Coins: ({{ userStore.coin }}/{{ currentOption.coin }})</span>
            <span v-if="currentOption.coin != 1000">Days: ({{ userStore.signInday }}/{{ currentOption.day }})</span>
        </div>
    </BiPopup>

</template>

<style scoped lang="scss">
@import url(./exchange.scss);
</style>